package thread;

import java.util.PriorityQueue;
import java.util.Timer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;

/**
 * @Author liangzai
 * @Description:
 */

class MyTask implements Comparable<MyTask> {
    private long time;
    private Runnable runnable;

    public MyTask(long time, Runnable runnable) {
        this.time = time;
        this.runnable = runnable;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }
}

class MyTimer{
    private Object locker = new Object();
    private PriorityQueue<MyTask> queue = null;

    public MyTimer(){
        queue = new PriorityQueue<>(1000);
        Thread thread = new Thread(()->{
            while(true) {
                synchronized (locker) {
                    try {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        long time = queue.peek().getTime();
                        if (time > System.currentTimeMillis()) {
                            locker.wait(time - System.currentTimeMillis());
                            continue;
                        }
                        Runnable runnable = queue.poll().getRunnable();
                        runnable.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }

    public void schedule(Runnable runnable, long time) throws InterruptedException {
        synchronized (locker){
            MyTask task = new MyTask(time+System.currentTimeMillis(),runnable);
            queue.offer(task);
            locker.notify();
        }
    }
}

public class Demo4 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer timer = new MyTimer();
        timer.schedule(()->{
            System.out.println("hello 3000");
        },3000);
        timer.schedule(()->{
            System.out.println("hello 2000");
        },2000);
        timer.schedule(()->{
            System.out.println("hello 1000");
        },1000);
    }
}
